package com.usian.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.mapper.ApLikesBehaviorMapper;
import com.usian.model.behavior.dto.LikesBehaviorDto;
import com.usian.model.behavior.pojos.ApBehaviorEntry;
import com.usian.model.behavior.pojos.ApLikesBehavior;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.pojos.ApUser;
import com.usian.service.ApBehariorEntryService;
import com.usian.service.ApLikeBehaviorService;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApLikeBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, com.usian.model.behavior.pojos.ApLikesBehavior> implements ApLikeBehaviorService {
   @Autowired
   private ApBehariorEntryService apBehariorEntryService;

    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //校验参数
        if(dto==null || dto.getArticleId()==null ||dto.getOperation()>1 ||dto.getOperation()<0){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询行为实体id ap——behavior——entry  id
        ApUser apUser = AppThreadLocalUtils.getUser();
        if(apUser!=null){
            ApBehaviorEntry entryId = apBehariorEntryService.findEntryId(apUser.getId(), dto.getEquipmentId());
            if(entryId==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"行为实体数据不存在");
            }

            //记录点赞行为 ap——like——behavior 点赞0 取消1
            ApLikesBehavior apLikesBehavior = this.getOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                    .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
                    .eq(ApLikesBehavior::getEntryId, entryId.getId()));
            if(apLikesBehavior==null){
                apLikesBehavior = new ApLikesBehavior();
                apLikesBehavior.setOperation(dto.getOperation());
                apLikesBehavior.setArticleId(dto.getArticleId());
                apLikesBehavior.setEntryId(entryId.getId());
                apLikesBehavior.setType(dto.getType());
                apLikesBehavior.setCreatedTime(new Date());
                save(apLikesBehavior);
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }else{
                apLikesBehavior.setOperation(dto.getOperation());
                this.updateById(apLikesBehavior);
                return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
            }
        }
        return null;
    }
}
